﻿@inherits BaseComponent

<div class="kui-app">
    @if (!IsHome)
    {
        <div class="kui-app-nav">
            @if (current?.Previous != null)
            {
                <span class="back" @onclick="e=>Back()">
                    <Icon Type="left" Theme="outline" />
                    <span>返回</span>
                </span>
            }
            @current?.Name
        </div>
    }
    <div class="@PageClass">
        <CascadingValue Value="this">
            <DynamicComponent Type="current?.ComType" Parameters="current?.ComParameters" />
        </CascadingValue>
    </div>
    @if (IsTab)
    {
        <AppTab Items="Menus" OnClick="OnTabClick" />
    }
</div>

@code {
    private Known.MenuItem current;
    private bool IsHome => current?.Id == "Home";
    private bool IsTab => current?.Previous == null;
    private string PageClass => CssBuilder.Default("kui-app-page").AddClass("nav", !IsHome).AddClass("tab", IsTab).BuildClass();

    [Parameter] public List<Known.MenuItem> Menus { get; set; }
    [Parameter] public Func<Task> OnLogout { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        current = Menus.FirstOrDefault();
    }

    public void Navigate(Known.MenuItem item)
    {
        if (item == null || item.ComType == null)
            return;

        item.Previous = current;
        current = item;
        StateChanged();
    }

    public void Back()
    {
        if (current?.Previous == null)
            return;

        current = current.Previous;
        StateChanged();
    }

    public Task LogoutAsync() => OnLogout?.Invoke();

    private void OnTabClick(Known.MenuItem info)
    {
        info.Previous = null;
        current = info;
        StateChanged();
    }
}